'''
@author: Aurelien Deharbe


This file is part of Cute-Server.

Cute-Server is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Cute-Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Cute-Server.  If not, see <http://www.gnu.org/licenses/>.
'''

from csessionprocess import CSessionProcess
import socket

class CSessionData(object):
    
    def __init__(self, sessid):
        print "[QServer] creating session " + sessid
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        bound = False
        while not bound:
            try:
                sock.bind(('', CSessionData.port))
                bound = True
            except socket.error:
                CSessionData.port = CSessionData.port + 1
        sock.listen(1)
        
        self._port = CSessionData.port
        self._sessid = sessid
        self._nb_clients = 0
        self._process = CSessionProcess(sessid, 'localhost', CSessionData.port)
        self._process.start()
        self._connection = sock.accept()[0]
        self._destroyed = False
        sock.close()
    
    def connectClient(self, host, port):
        self._connection.send("QSClient(" + host + "," + str(port) + ")\n")
        self._nb_clients = self._nb_clients + 1
    
    def removeClient(self, client):
        self._nb_clients = self._nb_clients - 1
        if self._nb_clients == 0:
            self.destroy()
    
    def destroy(self):
        if self._process:
            self._connection.send("QSQuit()\n")
            self._process.join(2)
            if self._process.is_alive():
                self._process.terminate()
                self._process.join()
        self._destroyed = True
        print "[QServer] session " + self._sessid + " destroyed"
    
    def isDestroyed(self):
        return self._destroyed
